import React, {Component} from 'react'
import {
    Text,
    View,
    StyleSheet,
    Button,
    TextInput,
    Image,
    FlatList,
    ScrollView,
    InteractionManager,
    Animated,
    TouchableOpacity, TouchableHighlight, ViewStyle
} from 'react-native'
import {inject, observer} from "mobx-react";
import styles, {margin, roundWithSize, padding, rectWithSize, border} from "../../style";
import CommonInput, {CommonInputInterface} from "../../component/common/CommonInput";
import {AppIcon} from "../../assets/icon/AppIcon";
import LineThroughText from "../../component/widget/LineThroughText";
import {Actions} from "react-native-router-flux";
import toast from "../../component/common/ToastProxy";
// import LoadingModal from "../../component/widget/LoadingModal";
import {IS_IOS} from "../../style/constant";
import {Store} from "../../store";
import {isPhoneAvailable} from "../../util";
import {WechatLogin} from "../../component/common/WechatProxy";
import {AlertButtonStyle, alertProxy} from "../../component/common/AlertProxy";
import {BaseTimer, DEFAULT_VERIFICATION_TIME_OUT} from "../../util/timer";
import hairlineWidth = StyleSheet.hairlineWidth;

interface FeatureBtnInterface {
    style?: ViewStyle,
    timerCount: number,
    onPress: () => any
}


@observer
class FeatureBtn extends Component<FeatureBtnInterface> {
    render() {
        const props = this.props;
        const disabled = props.timerCount !== 0;
        return (<TouchableOpacity {...props}
                                  activeOpacity={.6}
                                  disabled={disabled}
                                  style={[props.style, {
                                      borderRadius: 30,
                                      backgroundColor: disabled ? "#ccc" : "rgba(255,255,255,.5)"
                                  }, padding(6, 14), styles.centered]}><Text
            style={{
                color: "#fff",
                fontSize: 14
            }}>{props.timerCount === 0 ? '获取验证码' : `${props.timerCount}秒后重新发送`}</Text></TouchableOpacity>)
    }
}


interface LoginProps extends Store {
}

interface LoginState {
    phone: string,
    code: string,
    opacity: Animated.Value,
    timerCount: number,
}

@inject("user", "config")
@observer
export default class Login extends Component<LoginProps, LoginState> {

    state = {
        phone: null,
        code: null,
        opacity: new Animated.Value(0),
        timerCount: 0,
    };
    timer: BaseTimer = null;

    constructor(props) {
        super(props);

    }

    componentDidMount() {
        Animated.timing(this.state.opacity, {
            duration: 600,
            toValue: 1,
        }).start();
    }

    componentWillUnmount() {
        this.timer && this.timer.clearTimer();
    }

    getPhoneNumber = (phone: string) => {
        this.setState({phone});
    };
    getValidCode = (code: string) => {
        this.setState({code});
    };

    timerCallback = (timer: BaseTimer) => {
        this.setState({
            timerCount: timer.count
        })
    };

    sendVerificationCode = async () => {
        if (!isPhoneAvailable(this.state.phone)) return toast("请输入正确格式的手机号！");
        global.showLoading("发送中...");
        const code = await this.props.user.getVerificationCode(+this.state.phone);
        global.showSuccess("发送成功!");
        if (code !== 200) {
            return global.showError("发送验证码失败！");
        }
        this.timer = new BaseTimer(DEFAULT_VERIFICATION_TIME_OUT, this.timerCallback, 1000);
    };

    _renderForm() {
        const inputCmps: Array<CommonInputInterface> = [{
            icon: {
                name: "phone1",
                size: 16,
                color: "white"
            },
            inputStyle: {
                color: "#fff",
            },
            placeholder: "请输入手机号",
            keyboardType: "phone-pad",
            FeatureBtn: (<FeatureBtn timerCount={this.state.timerCount} onPress={this.sendVerificationCode}/>),
            getValue: this.getPhoneNumber
        }, {
            icon: {
                name: "ai-message",
                size: 16,
                color: "white"
            },
            inputStyle: {
                color: "#fff",
            },
            secureTextEntry: true,
            keyboardType: "phone-pad",
            placeholder: "请输入验证码",
            getValue: this.getValidCode
        }];
        return (
            <View style={{marginTop: 27}}>
                {inputCmps.map((inputProp, index) => {
                    return <CommonInput {...inputProp} key={index}/>
                })}
            </View>
        )
    }

    wechatLogin = () => {
        const loginHandle = () => WechatLogin(async (code) => {
            try {
                await this.props.user.loginByWechatAction(code);
            } catch (e) {
                console.log(e);
            }
            global.showSuccess("登录成功!");
            setTimeout(() => {
                Actions.reset("RootTabs");
            });

        });
        alertProxy("提示", "如果您是小程序用户,必须先重新登录一次小程序后,再点击微信登录按钮才能同步数据!", [{
            text: "前往登录",
            onPress: loginHandle
        }, {text: "取消", style: AlertButtonStyle.cancel}]);

    };

    _renderTips() {
        return (<View style={[styles.centerH, styles.flexDirectionRowNotFlex, {marginTop: 14}]}>
            <AppIcon name={"wuuiconsuotanhao"} size={16} color={"white"}/>
            <Text style={{fontSize: 12, marginLeft: 6, color: "#FFFFFF"}}>未注册过的用户将直接为您创建傻粮账户</Text>
        </View>)
    }

    _renderThirdLogin() {
        return this.props.config.installedWeChat ? (
            <View style={[styles.justifyEnd, styles.centerH, {paddingBottom: 10, marginTop: 30, height: 120}]}>
                <LineThroughText title={"微信登录"}/>
                <TouchableOpacity onPress={this.wechatLogin}>
                    <Image style={[{marginTop: 15}, rectWithSize(46)]}
                           source={require("../../assets/img/wechatIcon.png")}/>
                </TouchableOpacity>
            </View>
        ) : null;
    }

    // modal: LoadingModal;
    loginHandle = async () => {
        // if (this.props.user.verificationCode !== this.state.code) {
        //     return toast("验证码不正确,请输入正确验证码！");
        // }
        if (!this.state.phone) return;
        try {
            await this.props.user.loginAction(this.state.phone);
        } catch (e) {
            console.log(e);
        }
        const userModel = this.props.user.user;
        console.log(userModel);
        if (userModel.recommenderId) {
            global.showSuccess("登录成功！");
            Actions.reset("RootTabs");
        } else {
            alertProxy("提示", "请填写邀请码", [{text: "我知道了"}]);
            Actions.push("ShareCode");
        }
    };

    render() {
        const {opacity} = this.state;
        return (
            <Animated.View style={[LoginStyles.container, {opacity}]}>
                {/*<LoadingModal text={"加载中..."} backExit={false} ref={modal => this.modal = modal}/>*/}
                <ScrollView bounces={false} showsVerticalScrollIndicator={false} style={styles.flex}>
                    <Image source={require("../../assets/img/logo.png")}
                           style={[{marginTop: 21, alignSelf: "center", ...roundWithSize(137)}, border(1, "#fff")]}/>
                    {this._renderForm()}
                    <TouchableOpacity onPress={this.loginHandle} style={[styles.centered, {
                        backgroundColor: "rgba(255,255,255,0.4)",
                        paddingVertical: 10,
                        marginTop: 45,
                        borderRadius: 30
                    }]}>
                        <Text style={{color: "#fff", fontSize: 18}}>登录</Text>
                    </TouchableOpacity>
                    {this._renderTips()}
                    {this._renderThirdLogin()}
                </ScrollView>
            </Animated.View>
        )
    }
}


const LoginStyles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: "#629C36",
        paddingHorizontal: 20,
        paddingTop: "10%"
    }
});
